/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    bool leafSimilar(TreeNode *root1, TreeNode *root2)
    {
        vector<int> leaves1, leaves2;
        preorderAddLeaves(root1, leaves1);
        preorderAddLeaves(root2, leaves2);
        return leaves1 == leaves2;
    }

    void preorderAddLeaves(TreeNode *tree, vector<int> &leaves)
    {
        if (tree->left == nullptr && tree->right == nullptr)
        {
            leaves.push_back(tree->val);
            return;
        }
        if (tree->left != nullptr)
        {
            preorderAddLeaves(tree->left, leaves);
        }
        if (tree->right != nullptr)
        {
            preorderAddLeaves(tree->right, leaves);
        }
    }
};